package cn.broadmax.boot.modules.sys.controller;


import cn.broadmax.boot.base.SuperController;
import cn.broadmax.boot.log.SysLog;
import cn.broadmax.boot.modules.sys.entity.SysResource;
import cn.broadmax.boot.base.message.SResult;
import cn.broadmax.boot.modules.sys.bean.SysResourceTree;
import cn.broadmax.boot.modules.sys.service.ISysResourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 资源;菜单,按钮,页面 前端控制器
 * </p>
 *
 * @author jexx
 * @since 2020-07-07
 */
@Api(tags = "资源")
@RestController
@RequestMapping("/sys/resource")
public class SysResourceController extends SuperController {

    @Autowired
    private ISysResourceService sysResourceService;

    @ApiOperation("新增菜单或者按钮")
    @SysLog(value = "新增资源")
    @PostMapping(value = "")
    public SResult<SysResource> addResource(@RequestBody SysResource resource){
        sysResourceService.save(resource);
        SysResource sysResource = sysResourceService.getById(resource.getId());
        return SResult.ok("", sysResource);
    }

    @ApiOperation("根据主键删除菜单或者按钮")
    @SysLog(value = "删除资源")
    @DeleteMapping(value = "/{resourceId}")
    public SResult<Boolean> deleteResourceById(@PathVariable String roleId){
        boolean success = sysResourceService.removeById(roleId);
        return SResult.ok("", success);
    }

    @ApiOperation("根据主键更新资源, 父资源ID和资源类型不能更新")
    @SysLog(value = "更新资源")
    @PutMapping(value = "/{resourceId}")
    public SResult<SysResource> updateResourceById(@PathVariable String resourceId, @RequestBody SysResource resource){
        resource.setId(resourceId);
        resource.setParentId(null);
        resource.setType(null);
        sysResourceService.updateById(resource);

        resource = sysResourceService.getById(resourceId);
        return SResult.ok("", resource);
    }

    @ApiOperation("获取资源树")
    @GetMapping(value = "/tree")
    public SResult<List<SysResourceTree>> getTreeResources(){
        List<SysResource> list = sysResourceService.list();
        List<SysResourceTree> resourceTrees = SysResourceTree.buildResourceTree(list);
        return SResult.ok("", resourceTrees);
    }

}
